package metrictransformer

import (
	"github.com/project-flogo/core/data"
	"github.com/project-flogo/core/data/coerce"
	"github.com/project-flogo/core/data/mapper"
	"github.com/project-flogo/core/data/resolve"
)

type Transformer interface {
	Trans(values map[string]interface{}) (interface{}, error)
	String() string
}

type exprTransformer struct {
	key    string
	mapper mapper.Mapper
}

func NewExprTransformer(params interface{}) (Transformer, error) {
	expr, err := coerce.ToString(params)
	if err != nil {
		return nil, err
	}
	return newExprTransformer(expr)
}

func newExprTransformer(expr string) (*exprTransformer, error) {
	f := mapper.NewFactory(resolve.GetBasicResolver())
	mappings := map[string]interface{}{
		"key": expr,
	}
	mapper, err := f.NewMapper(mappings)
	if err != nil {
		return nil, err
	}
	et := exprTransformer{
		key:    "key",
		mapper: mapper,
	}
	return &et, nil
}

func (e *exprTransformer) Trans(values map[string]interface{}) (interface{}, error) {
	scope := data.NewSimpleScope(values, nil)
	results, err := e.mapper.Apply(scope)
	if err != nil {
		return nil, err
	}
	return results[e.key], nil
}

func (e *exprTransformer) String() string {
	return "exprTransformer"
}
